package net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 网络编程练习-服务端
 */
public class NetExercise01Server {

    public static void main(String[] args) throws Exception {

        /*
            1)使用字符流的方式，编写一个客户端程序和服务端程序
            2)客户端发送"name"，服务端接收后，返回 "我是nova"
            3)客户端发送"hobby"，服务端接收后，返回 "编写java程序"
            4)不是这两个问题，回复"你说啥呢"
         */

        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待客户端请求...");

        Socket socket = serverSocket.accept();
        System.out.println("开始通信..." + socket);

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        String question = null;
        while ((len = inputStream.read(buffer)) != -1) {
            question = new String(buffer, 0, len);
            System.out.println("客户端请求：" + question);
        }
        if (question == null) {
            outputStream.write("请输入问题".getBytes());
        } else {
            if (question.equals("name")){
                outputStream.write("我是nova".getBytes());
            } else if (question.equals("hobby")){
                outputStream.write("编写java程序".getBytes());
            } else {
                outputStream.write("你说啥呢".getBytes());
            }
        }
        socket.shutdownOutput();

        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("服务端退出...");

    }
}
